/*
 * 用户基本资料管理
 * @author 醉雪
 * @time 2018/10/17
 * @since 1.0.0
 * */
// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form, Select, Input, DatePicker, Button, Row, Col, Cascader, Table } from 'antd'
import moment from 'moment';
const { RangePicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './promoteTheCustomerStyle.less'
import classnames from 'classnames/bind';
let cx = classnames.bind(styles);
const Option = Select.Option;
const FormItem = Form.Item;
import { listConfig } from 'config/config'
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const formItemLayout = {
  labelCol: {
    span: 5
  },
  wrapperCol: {
    span: 10
  },
}
const infoListAdminView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let { areaList, listData, formParams, detailData, productIds } = modelObj;
  console.log(listData, detailData, 'listData');
  // modelObj.xxx获取model中状态机的值

  const columns = [
    // { title: '序号', dataIndex: 'name', key: 'name' },
    {
      title: '省份城市', dataIndex: 'cityName', key: 'cityName',
      width:150,
      render: (text, item, index) => {
        return  `${item.provinceName||''}${item.provinceName&&item.cityName&&' - '||' '}${item.cityName||''}`
      }
    },
    { title: '推荐美房', dataIndex: 'productName', key: 'productName', },
    { title: '推荐人', dataIndex: 'recommendUser', key: 'recommendUser' },
    { title: '推荐人类型', dataIndex: 'recommendUserType', key: 'recommendUserType' },
    { title: '指定置业顾问', dataIndex: 'consultant', key: 'consultant', },
    { title: '推荐状态', dataIndex: 'recommendStatus', key: 'recommendStatus',width:60,
      render (value, item, index){
        return {'0':'失败','1' :'成功'}[value]
      }
    },
    { title: '推荐时间', dataIndex: 'recommendTime', key: 'recommendTime' },
    { title: '客户姓名', dataIndex: 'clientName', key: 'clientName', },
    { title: '客户电话', dataIndex: 'clientPhone', key: 'clientPhone' ,width:130},
    { title: '剩余保护期', dataIndex: 'protectDate', key: 'protectDate' },
    { title: '客户状态', dataIndex: 'clientStatus', key: 'clientStatus',
      render (value, item, index) {
        return {'10':'待跟进','20':'验证通过','30':'已跟进','40':'已认筹','50':'已认购','60':'已签约','70':'已结算','80':'已作废','90':'已关闭'}[value]
      }
    },
  ];
  const recommendStatusList = [
    {
      value: '0',
      label: '失败'
    },
    {
      value: '1',
      label: '成功'
    }
  ];
  const customerStatusList = [
    {
      value: '10',
      label: '待跟进'
    },
    {
      value: '20',
      label: '验证通过'
    },
    {
      value: '30',
      label: '已跟进'
    },
    {
      value: '40',
      label: '已认筹'
    },
    {
      value: '50',
      label: '已认购'
    },
    {
      value: '60',
      label: '已签约'
    },
    {
      value: '70',
      label: '已结算'
    },
    {
      value: '80',
      label: '已作废'
    },
  ];
  // 分页
  const pagination = {
    current: Number(detailData.pageNo || 1),
    pageNo: Number(detailData.pageNo || 1),
    pageSize: Number(detailData.pageSize || 10),
    total: Number(detailData.total),
    showTotal: e => '共 ' + detailData.total + ' 条',
    showSizeChanger: true,
    showQuickJumper: true,
    onChange: changePage, //分页事件
    onShowSizeChange: changePage, //每页条数
  }
  //翻页函数
  function changePage(pageNo, pageSize) {
    dispatch({
      type: `${namespace}/getPromoteList`,
      payload: { pageNo: pageNo, pageSize }
    });
  }
  //model数据更新
  function inputChange(name, value) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: Object.assign(queryCondition, { [name]: value })
    });
  }
  function selectCity(val) {
    formParams.province = val[0];
    formParams.city = val[1];
    formParams.area = val[2];
    // 获取项目列表
    dispatch({
      type: `${namespace}/updateStore`,
      payload: ({ formParams })
    });
    dispatch({ type: `${namespace}/houseListGet`, payload: { province: val[0], city: val[1] } });
  }
  function productNameChange(val) {
    console.log(val);
    formParams.productName = val;
    // 获取项目列表
    dispatch({
      type: `${namespace}/updateStore`,
      payload: ({ formParams })
    });
  }
  function recommendStatusChange(val) {
    console.log(val);
    formParams.recommendStatus = val;
    // 获取项目列表
    dispatch({
      type: `${namespace}/updateStore`,
      payload: ({ formParams })
    });
  }
  function clientStatusChange(val) {
    formParams.clientStatus = val;
    // 获取项目列表
    dispatch({
      type: `${namespace}/updateStore`,
      payload: ({ formParams })
    });
  }
  function getFromDate(dates, dateStrings) {
    console.log('From: ', dates[0], ', to: ', dates[1]);
    console.log('From: ', dateStrings[0], ', to: ', dateStrings[1]);
    formParams.startTime = dateStrings[0];
    formParams.endTime = dateStrings[1];
    formParams.dateData = dates;
    dispatch({
      type: `${namespace}/updateStore`,
      payload: ({ formParams })
    });
  }
  function searchList() {
    console.log(formParams);
    let obj = { ...formParams, pageNo: detailData.pageNo, pageSize: detailData.pageSize || 10, productIds };
    delete obj.dateData;
    delete obj.province;
    delete obj.city;
    delete obj.area;
    dispatch({ type: `${namespace}/getPromoteList`, payload: obj });
  }
  
  //导出
  async function downLoad() {
    await dispatch({
      type: `${namespace}/downLoad`,
      payload: { activityId }
    });
  }
  
  return (
    <div className="public_listMain">
      <div className="functionButton">
        <Button type="primary" loading={modelObj.exportLoading} onClick={() =>{
          dispatch({
            type: `${namespace}/exportFile`,
            payload: {}
          })
        }}>导出</Button>
      </div>
      <div className="boxShadow">
    <div className={cx('promote')}>
      <div style={{ marginBottom: 48, background: '#fff', padding: '16px' }}>
        <Row>
          <Col {...listConfig.searchCol}>
            <FormItem {...listConfig.searchFormItem} label="省市" labelCol={{ span: 5 }}>
              <div className={cx('select-item-contain')}>
                <Cascader
                  value={[formParams.province, formParams.city, formParams.area]}
                  options={areaList}
                  onChange={selectCity}
                  placeholder="请选择省市" />
              </div>
            </FormItem>
          </Col>
          <Col {...listConfig.searchCol}>
            <FormItem {...listConfig.searchFormItem} label="推荐美房" labelCol={{ span: 5 }}>
              <div className={cx('select-item-contain')}>
                <Input value={formParams.productName} placeholder='请输入推荐美房' onChange={(e) => { productNameChange(e.target.value) }} />
              </div>
            </FormItem>
          </Col>
          <Col {...listConfig.searchCol}>
            <FormItem {...listConfig.searchFormItem} label="推荐状态" labelCol={{ span: 6 }}>
              <div className={cx('select-item-contain')}>
                <Select value={formParams.recommendStatus}
                  onChange={(e) => { recommendStatusChange(e) }}
                  placeholder='请选择推荐状态'>
                  {
                    recommendStatusList.map((item, index) => {
                      return (
                        <Option key={index} value={item.value}>
                          {item.label}
                        </Option>);
                    })
                  }
                </Select>
              </div>
            </FormItem>
          </Col>
          <Col {...listConfig.searchCol}>
            <FormItem {...listConfig.searchFormItem} label="客户状态" labelCol={{ span: 6 }}>
              <div className={cx('select-item-contain')}>
                <Select value={formParams.clientStatus}
                  onChange={(e) => { clientStatusChange(e) }}
                  placeholder='请选择客户状态'>
                  {
                    customerStatusList.map((item, index) => {
                      return (
                        <Option key={index} value={item.value}>
                          {item.label}
                        </Option>);
                    })
                  }
                </Select>
              </div>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <Col span={6}>
            <FormItem {...formItemLayout} label="推荐时间" >
              <div className={cx('select-item-contain')}>
                <RangePicker
                  ranges={{ '今天': [moment(), moment()], '这个月': [moment(new Date().getTime() - 3600 * 1000 * 24 * 30), moment(new Date())] }}
                  showTime
                  value={formParams.dateData}
                  format="YYYY-MM-DD"
                  onChange={getFromDate}
                />
              </div>
            </FormItem>

          </Col>
          <Col span={18}>
            <div style={{ display: 'flex', justifyContent: 'flex-end', alignItems: 'center', paddingRight: '32px' }}>
              <Button type="primary" style={{ marginRight: '16px' }} onClick={(e) => { searchList() }} loading={modelObj.loading}>搜索</Button>
              <Button  onClick={() => {
                dispatch({
                  type: `${namespace}/updateStore`,
                  payload: ({ formParams: {}, productIds: [] })
                })
              }}>重置</Button>
            </div>
          </Col>
        </Row>
      </div>
      
      <Table
        columns={columns}
        dataSource={listData}
        pagination={pagination}
      />
    </div>
      </div>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(infoListAdminView))
